<template>
  <div >
    <Row style="display: flex">

      <!--折叠时-->
      <i-col :xs="{ span: 0, offset: 0 }"  :sm="{ span: 1, offset:0 }"
              v-if="isExpanded&&!isMobile" class-name="sideMenus">
        <div style="background: #333;min-height: 38rem" >
          <Button type="text" ghost style="margin-top: 1rem" size="small" @click="backToIndex">首页</Button>
          <ul style="padding-top: 1rem" class="menu_small">
            <ol v-for="(item,index) in urls.Moudle" v-if="hasAuth(item.path)" >
              <Tooltip placement="right">
              <Icon :type="item.icon"   size="20" class="menu_pop_icon" :title="item.title" />
                <div slot="content">
                  <p v-for="(shelf,sIndex) in item.children" v-if="hasAuth(shelf.path)" class="menu_pop_item" @click="skipToMenu(shelf)">
                    {{shelf.title}}
                  </p>

                </div>
              </Tooltip>
            </ol>
          </ul>
        </div>
      </i-col>

      <!--展开时-->
      <i-col  :xs="{ span: 0, offset: 0 }"  :sm="{ span: 4, offset:0}" class-name="sideMenus"
              v-if="!isExpanded&&!isMobile"   >
        <div style="width: 100%">
          <h1  class="header_title">
            <span type="text" @click="backToIndex" class="header_title" title="返回首页" >{{$site.siteName}}</span>
          </h1>
        </div>

        <Menu theme="dark" active-name="1"  class="menu_big" @on-select="skipToMenu"
                 :open-names="['1']" accordion>
            <Submenu :name="item.title" v-for="(item,index) in urls.Moudle" v-if="hasAuth(item.path)">
              <template slot="title">
                <Icon :type="item.icon" />
                  {{item.title}}
              </template>
              <MenuItem :name="shelf" v-for="(shelf,sIndex) in item.children" v-if="hasAuth(shelf.path)"  :to="shelf.path">
                {{shelf.title}}
              </MenuItem>

            </Submenu>

        </Menu>
      </i-col>


      <Drawer title="管理后台"  placement="left" :closable="true" v-model="isMobileMenu" v-if="isMobile" class-name="menu_drawer" >
        <Menu theme="dark" active-name="1"  class="menu_big" @on-select="skipToMenu"
              :open-names="['1']" accordion>
          <Submenu :name="item.title" v-for="(item,index) in urls.Moudle" v-if="hasAuth(item.path)">
            <template slot="title">
              <Icon :type="item.icon" />
              {{item.title}}
            </template>
            <MenuItem :name="shelf" v-for="(shelf,sIndex) in item.children" v-if="hasAuth(shelf.path)"  :to="shelf.path">
              {{shelf.title}}
            </MenuItem>

          </Submenu>

        </Menu>
      </Drawer>


      <!--右侧区域-->
      <i-col   :xs="{ span: 24, offset: 0 }" :sm="{ span: isExpanded?23:20, offset:isExpanded?1:4 }">
        <Row class="header">
          <div style="display: flex;align-items: center;flex-grow: 2">
            <Icon type="md-apps" size="18" style="padding: 0rem 1rem;cursor: pointer;"
                  title="展开侧边栏" v-show="isExpanded||isMobile" @click="switchExpand(false)" />
            <Icon type="md-expand" size="18" style="padding: 0rem 1rem;cursor: pointer;" v-if="!isMobile"
                  title="全屏展示" v-show="!isExpanded" @click="switchExpand(true)"/>
            <!--当前路径-->
            <Breadcrumb style="font-size: 13px;" >
              <BreadcrumbItem to="/work/dashboard" v-if="currentRouter.parent!==''&&!isMobile" ><span style="color: #999;" >
                首页</span>
              </BreadcrumbItem>
              <BreadcrumbItem to="" v-if="currentRouter.parent!==''"><span style="color: #999;" >
                {{currentRouter.parent}}</span>
              </BreadcrumbItem>
              <BreadcrumbItem v-if="currentRouter.shelf!==''">
                <span style="color: #666;font-weight: 500" >{{currentRouter.shelf}}</span>
              </BreadcrumbItem>
            </Breadcrumb>
          </div>

          <!--欢迎-->
          <div  style="text-align:center;padding: 0 0.5rem" >
            <Select @on-change="changeTimeLocal()" v-model="timeZoneOffset" size="small" style="width:180px;font-size: 12px !important;margin: 0 0.5rem">
              <Option v-for="item in timezones" :value="item.offset" :key="item.name" >{{ item.name }}</Option>
            </Select>
<!--            <Tag>{{bjtTime?"北京时间模式":"UTC 时间模式"}}</Tag>-->
            <Dropdown @on-click="userMenuClicked"  trigger="click">
              <a href="javascript:void(0)" style="color: #2c3e50;font-size: 12px;font-weight: 500;text-transform: uppercase">
                {{username}}
                <Icon type="ios-arrow-down"></Icon>
              </a>
              <DropdownMenu slot="list" style="margin-right: 3rem">
                <DropdownItem v-mobile="false">
                  <Checkbox v-model="user_menu_tabs">标签导航</Checkbox>
                </DropdownItem>
<!--                <DropdownItem v-mobile="false" >-->
<!--                  <Checkbox v-model="bjtTime" @on-change="changeTimeLocal()">北京时间</Checkbox>-->
<!--                </DropdownItem>-->
                <DropdownItem name="logout" divided>退出登录</DropdownItem>
              </DropdownMenu>
            </Dropdown>
          </div>
        </Row>
        <!---Tag分页标签-->
        <Row style="padding: 0.5rem;border-bottom: solid 1px #f3f3f6"  v-show="!this.$yMobile()&&historys.length>0&&user_menu_tabs">
          <div id="tabs_parent"  >
          <span class="tab_back"  @click="tabScrollBack()" v-show="!hideTabsArrow">
            <Icon type="ios-arrow-back" />
          </span>
          <span class="tab_next"  @click="tabScrollNext()" v-show="!hideTabsArrow">
              <Icon type="ios-arrow-forward" />
          </span>

          <div id="tabs_scroll">
              <div  id="tabs_scroll_items"  :style="{'transform':'translateX(-'+tabsTransformX+'px)'}" >
                <div class="tab_item" v-for="(item,index) in historys">
                  <span :class="historyIndex===index?'tab_title_current':'tab_title' " @click="switchTo(item)">{{item.title}}</span>
                  <Icon type="ios-close" class="tab_icon" @click="removeFromHistory(item)" ></Icon>
                </div>

              </div>
            </div>
          </div>

        </Row>


        <div style="padding-top: 0.5rem;padding-bottom: 3rem;padding-left: 1rem;padding-right: 1rem">
          <router-view></router-view>
        </div>

      </i-col>
    </Row>




  </div>
</template>

<!--javascript 代码-->
<script>
  import URL_MAIN from "./js/baseUrl"
  import RouterUrls from './js/RouterUrls'
  import MTypes from "../store/types/TypesMutation"

  export default {
    data(){
      return {
        urls: [],
        isMobileMenu:false,
        username: this.$store.getters.userInfo.userName,
        currentRouter:{
          parent:'',
          shelf:''
        },
        historys:[],
        historyIndex: -1,
        tabsTransformX:0,
        hideTabsArrow:true,
        user_menu_tabs:true,
        // bjtTime:true,
        timeZoneOffset:8,
        //https://www.zeitverschiebung.net/cn/city/2988507
        timezones:[
          {name:"北京时间: GTM+8",offset:8},
          {name:"纽约时间: GTM-5",offset:-5},
          {name:"伦敦时间: GTM+0",offset:0},
          {name:"墨西哥时间: GTM-6",offset:-6},
          {name:"巴西时间: GTM-3",offset:-3},
          {name:"德国/法国: GTM+1",offset:1}
        ]
      }
    },
    computed:{
      isExpanded () {
        if(this.$route.path === '/index'){
          return true;
        }else{
          return this.$store.state.base.isExpanded
        }
      },
      isMobile(){
      return this.$yMobile()
      }


    },
    methods: {
      resetTabsPosition(){
        var arrowWidth = 32;
        var that = this;
        setTimeout(function () {
          var tabsVisibleDom = document.getElementById("tabs_parent").getBoundingClientRect() ;
          var tabsDom =  document.getElementById("tabs_scroll_items").getBoundingClientRect() ;
          // console.log(tabsVisibleDom.width);
          // console.log(tabsDom.width);
          if (tabsVisibleDom.width===0||tabsDom.width===0){
            return;
          }
          //64为两侧arrow的宽度
          that.hideTabsArrow = tabsVisibleDom.width>=(tabsDom.width+arrowWidth*2) ;
          that.tabsTransformX = 0
        },500);



      },
      tabScrollNext(){
        var arrowWidth = 32;
       var tabsVisibleDom = document.getElementById("tabs_parent").getBoundingClientRect() ;
       var tabsDom =  document.getElementById("tabs_scroll_items").getBoundingClientRect() ;
        var minStep = tabsVisibleDom.width/2;

       var maxOffset = tabsDom.width - tabsVisibleDom.width + arrowWidth*2;
       let visibleSteps = maxOffset - this.tabsTransformX
       if (visibleSteps >minStep){
         this.tabsTransformX+=minStep;
       }else{
         this.tabsTransformX = maxOffset;
       }
      },
      tabScrollBack(){
        var arrowWidth = 32;

        var tabsVisibleDom = document.getElementById("tabs_parent").getBoundingClientRect() ;
        var tabsDom =  document.getElementById("tabs_scroll_items").getBoundingClientRect() ;
        var minStep = tabsVisibleDom.width/2;
        var minOffset = 0
        let visibleSteps = this.tabsTransformX;
        if (visibleSteps > minStep){
          this.tabsTransformX-=minStep;
        }else{
          this.tabsTransformX = minOffset;
        }


      },


      backToIndex(){
        this.$router.replace('/work/dashboard');
        this.currentRouter.shelf = "";
        this.currentRouter.parent = "";
      },
      hasAuth(path){
        return this.$authority(path);
      },
      skipToMenu(shelf){
        this.isMobileMenu = false;
        if (!this.$yMobile()){
          this.addToHistory(shelf);
        }
        var self = this;
        this.$router.push({ path: shelf.path}, function () {
            self.refreshTopNavigation(shelf.path);
          })
      },
      switchTo(shelf){
       this.historyIndex  = this.historys.yIndexOf(shelf)
        var self = this;
        this.$router.push({ path: shelf.path}, function () {
          self.refreshTopNavigation(shelf.path);
        })
      },
      changeTimeLocal(event){
        this.$store.commit('setBJTime',this.timeZoneOffset);
        console.log("changeTimeLocal: "+this.timeZoneOffset);
        this.$Message.info('当前时区: '+(this.timeZoneOffset>=0?"+":"")+this.timeZoneOffset+", 暂不支持夏令时");
      },
      switchExpand(isExpand){
        if (this.isMobile){
          this.isMobileMenu = true;
        }else{
          this.$store.commit('setUIExpanded',isExpand);
        }
      },
      removeFromHistory(shelf){
        if (this.historys.yHas(shelf)){
          this.historys.yRemove(shelf)
          this.resetTabsPosition()
        }
      },
      addToHistory(shelf){
        let index = this.historys.yIndexOf(shelf);
        if (index===-1){
          this.historys.push(shelf);
          this.historyIndex = this.historys.length-1;
        }else{
          this.historyIndex = index
        }
        this.resetTabsPosition()
      },
      userMenuClicked(name){
        if (name ==="logout"){
          this.logout();
        }

      },
      logout(){
        var self = this;
        this.$apiMain.logOut({userId:self.$store.getters.userInfo.id}).then(function (response) {
          self.$store.commit(MTypes.user.clearUserInfo);
          self.$router.replace(URL_MAIN.ALogin);
        });
      },
      refreshTopNavigation(path){
        var cPath = path;
        var parent =  this._.filter(RouterUrls.Moudle,function (item) {
          return cPath.indexOf(item.path+'/')!==-1;
        });
        if (parent.length>0){
          var shelf = this._.filter(parent[0].children,function (item) {
            return cPath === item.path;
          });
          this.currentRouter.parent = parent[0].title;
          if (shelf.length>0){
            this.currentRouter.shelf = shelf[0].title;
          }else{
            this.currentRouter.shelf = ""
          }
        }else{
          this.currentRouter.parent = ""
        }

      },

    },
    components: {

    },
    created(){
      var self = this;
      this.$apiMain.index().then(function (response) {
        if (!response.success) {
          self.$router.push('/login');
        }
      });

      self.urls = RouterUrls;

    },
    mounted(){
      this.changeTimeLocal();
      if (this.$route.path.indexOf("/user/ChatMessageDetail") < 0 && this.$router.path===undefined){
          this.$router.push('/work/dashboard');
          this.currentRouter.shelf = "";
          this.currentRouter.parent = "";
        }

      //监听窗口变化
      const that = this
      window.onresize = () => {
        return (() => {
         that.resetTabsPosition();
        })()
      }

    }
  }
</script>

<!--css样式-->
<style scoped lang="less">
@import  (once,optional) "css/base";

  .sideMenus{

    position: fixed;
    height: 100vh;
    z-index: 999;

  }

  .header_title{
    font-weight: 800;
    font-size: 1.3em;
    cursor: pointer;
    min-height: 3.2rem;
    background: #333;
    padding-top: 0.3rem;
    color:white;
    text-align: center;
  }

  .menu_pop_item{
    padding: 0.5rem 1rem;
    cursor: pointer;
  }
  .menu_pop_item:hover{
    color:@tiyPrimaryColor
  }

  .menu_pop_icon{
    padding: 1rem;
    cursor: pointer;
    color: white;
  }
  .menu_pop_icon:hover{
    color:@tiyPrimaryColor
  }
  ::-webkit-scrollbar {
    /*隐藏滚轮*/
    display: none;
  }

  .menu_big{
    text-align: left;
    height: calc(100vh - 8.5rem);
    overflow-y: auto;
    position: static;
    max-width: 100%;
  }

  .menu_small{
    overflow-y: auto;
    position: static;
    max-width: 100%;
    text-align: left;
    height: calc(100vh - 8.5rem);
  }

  .header {
    //background:linear-gradient(90deg,#1d42ab,#2173dc,#1e93ff);
    display: flex ;
    align-items: center;
    padding-top: 1rem;
    padding-bottom: 1rem;
    box-shadow: 1px 0px 6px #8d8d8d;


  }
  .card_css {
    margin-bottom: 1rem;
    margin-top: 1rem;
    padding: 0rem 1rem;
    cursor: pointer;
  }

  .card_icon {
    margin-top: 8px;
    margin-bottom: 8px;
  }
  .log_out{
    font-size: 1em;
    cursor: pointer;
  }
  .ivu-drawer-body{
    padding: 0px!important;
  }





  /******tabs******/

  #tabs_parent{
    min-width: 100%;
    position: relative;
    padding: 0 32px;
    //background: #f3f3f6;
    #tabs_scroll{
      overflow: hidden;
      white-space: nowrap;
    }
    .tab_back{
      width: 32px;
      position: absolute;
      left: 0;
      line-height: 32px;
      cursor: pointer;
      background: white;
      i{
        color: #333;
      }
    }
    .tab_next{
      .tab_back;
      right: 0;
      left: unset;
    }

    .tab_item {
      display: inline-block;
      cursor: pointer;
      border: solid 1px @tiyBorderColor;
      margin: 0.2rem ;
      border-radius: 3px;
    }

    #tabs_scroll_items{
      white-space: nowrap;
      padding-left: 0;
      margin: 0;
      float: left;
      list-style: none;
      box-sizing: border-box;
      position: relative;
      transition: transform .5s ease-in-out;
    }

    .tab_title{
      font-size: 12px;
      color: #666;
      padding: 0.2rem  0.2rem 0.2rem 1rem;
      display: inline-block;
      height: 100%;
      vertical-align: middle;
    }
    .tab_title_current{
      .tab_title;
      color: @tiyPrimaryColor;
    }
    .tab_icon{
      font-size: 1.1rem;
      padding: 0.2rem 0.3rem;
      color: #999;
      display: inline-block;
      height: 100%;
      vertical-align: middle;
    }
    .tab_icon:hover,.tab_title:hover{
      color: #333;
    }

  }





</style>
